var express = require('express')
var router = express.Router()
const axios = require('axios')
const crypto = require('crypto')

router.post('/login', async (req, res) => {
  const { code } = req.body
  let { data } = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=wx448da31cbe9a8458&secret=cbf32c052e705f49445422a20f9f198c&grant_type=authorization_code&js_code=${code}`)
  res.send(JSON.stringify(data))
})

router.post('/check', async (req, res) => {
  const { openid, session_key } = req.body
  const hmac = crypto.createHmac('sha256', '')

  hmac.update(session_key)
  let sign = hmac.digest('hex')
  console.log(sign)
  let s1 = await axios.get(' https://api.weixin.qq.com/wxa/checksession', {
    params: {
      signature: sign,
      openid: openid,
      access_token: session_key,
      sig_method: 'hmac_sha256'
    }
  })
  console.log(s1.data)
  res.send(JSON.stringify(s1.data))
})
module.exports = router

const { KEYUTIL, KJUR, hextob64, hextob64u } = require('jsrsasign')

const privateKeyString = `
-----BEGIN PRIVATE KEY-----
GET\n/v3/certificates\n1554208460\n593BEC0C930BF1AFEB40B4A08C8FB242\n\n
-----END PRIVATE KEY-----
`
let s = `
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQChAE3k5l5qcPwd
VIUiHxAQdOpDxtQnZfPragcw3g+/ubAY/PfRmPnah1XQAPIHZ2Ku9syJaE5REuWf
CMxNGLrcchEaEZ6f2iSuK2OmhJefME2A3n/BExZQm/jwMRz2BWH1zs3tTp5LtdxU
z8mIBu+p5xiYCwZSK+CGSUr57zGjiK9KEr5XhJy9NvxHct0Mg2rpYHqmKxJyNxtw
g6eTZqAxwTEgvnKjK9W9OqlDRVu260taUCVmOgbwL8Dsq1ds9NBivauR8bMy0i2F
1SZI6VjSNY4lfde/w68nsJJuMcLs17FgoieXnMZhQz5M85HKy7OiJYOdywxnk1ie
mVMIihWDAgMBAAECggEAJB9dWq4VIOyYpDwCYtV1VTvmE67Yir5lK7xuQJiSEAIp
cHHRaEVaSZ1zs2eC5gZcLcVRvsKYT7hdrIDc1a9mvW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NJtpOSNt6kjRsj1/u7jKPBl0IvoUPpafSzJCMK5dCB1trBcF
s8r5F51HDQBnQGYNcKV3cik=
-----END PRIVATE KEY-----
`

function sha256withRSA(inputString) {
  const key = KEYUTIL.getKey(privateKeyString)
  // 创建 Signature 对象，设置签名编码算法
  const signature = new KJUR.crypto.Signature({ alg: 'SHA256withRSA' })
  // 初始化
  signature.init(key)
  // 传入待加密字符串
  signature.updateString(inputString)
  // 生成密文
  const originSign = signature.sign()
  // const sign64 = hextob64(originSign);
  // console.log('sign base64 =======', sign64);
  const sign64u = hextob64u(originSign)
  console.log('sign base64u=======', sign64u)
  return originSign
}
// sha256withRSA(s)
